package j02zuoye;

class Card{
    int balance = 88;
    /*
    存钱
    只要balance小于100，就让balance增加2000(同时打印"向银行卡中存入了2000元，当前账户余额是xxx"，xxx是balance的值)，balance大于等于100时，打印"已经有钱花了，等没钱的时候再存!"，并停止继续存钱, 等待余额小于100才继续存钱。
     */
    public void depositMoney(){
        if(balance<100){
            balance += 2000;
            System.out.println("妈妈向银行卡中存入了2000元，当前账户余额是"+balance);
            //通知
            synchronized (Z2.lock){
                Z2.lock.notify();
            }
        }else {
            System.out.println("已经有钱花了，等没钱的时候再存!");
            //等待
            synchronized (Z2.lock){
                try {
                    Z2.lock.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
    /*
    取钱
    只要balance大于等于100，就让balance减少100(同时打印"从银行卡中取出了100元，当前账户余额是xxx"，xxx是balance的值)，balance小于100时，打印"没钱花了，等有钱的时候再取!"，并停止继续取钱, 等待余额大于100才继续取钱。
     */
    public void withdrawCash(){
        while (true){
            if(balance>=100){
                balance -= 100;
                System.out.println("小明从银行卡中取出了100元，当前账户余额是"+balance);
            }else {
                System.out.println("没钱花了，等有钱的时候再取!");
                synchronized (Z2.lock){
                    Z2.lock.notify();
                    try {
                        Z2.lock.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }
}
class Mother implements Runnable{
    Card card;

    public Mother(Card card) {
        this.card = card;
    }

    @Override
    public void run() {
        while (true){
            card.depositMoney();
        }
    }
}
class Son implements Runnable{
    Card card;

    public Son(Card card) {
        this.card = card;
    }

    @Override
    public void run() {
        while (true){
            //取钱
            card.withdrawCash();
        }
    }
}
public class Z2 {
    static Object lock = new Object();
    public static void main(String[] args) {
        Card card = new Card();

        Mother mother = new Mother(card);
        Son son = new Son(card);
        new Thread(mother).start();
        new Thread(son).start();
    }
}
